package com.tang.servlet.model;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.tang.bean.*;
import com.tang.constants.BookStoreConstants;
import com.tang.services.OrderService;
import com.tang.services.impl.OrderServiceImpl;
import com.tang.servlet.base.ModelBaseServlet;
import com.tang.utils.JsonUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class OrderClientServlet extends ModelBaseServlet {
  private OrderService orderService = new OrderServiceImpl();
  //订单结算
  public void checkout(HttpServletRequest request, HttpServletResponse response) throws IOException {
    try {
      //1. 从session中获取购物⻋信息
      HttpSession session = request.getSession();
      Cart cart = (Cart) session.getAttribute(BookStoreConstants.CART_SESSIONKEY);
      //2. 从session中获取用户信息
      User user = (User) session.getAttribute(BookStoreConstants.LOGINUSER_SESSIONKEY);
      //3. 调用业务层的方法，进行订单结算，并且获取订单的序列号
      String orderSequence = orderService.checkout(cart,user);
      //4. 清空购物⻋
      session.removeAttribute(BookStoreConstants.CART_SESSIONKEY);
      //5. 将订单序列号存储到请求域对象中，并且跳转到checkout.html⻚面
      request.setAttribute("orderSequence",orderSequence);
      processTemplate("cart/checkout",request,response);
    } catch (Exception e) {
      e.printStackTrace();
      processTemplate("error", request, response);
      throw new RuntimeException(e.getMessage());
    }
  }

  //跳转到用户订单页面
  public void toUserOrderPage(HttpServletRequest request, HttpServletResponse response)
          throws IOException {
    processTemplate("order/order",request,response);
  }

  //跳转到管理者订单页面
  public void toManagerOrderPage(HttpServletRequest request, HttpServletResponse response)
          throws IOException {
    processTemplate("manager/order_manager",request,response);
  }

    //用户订单页面
    public void orderPage(HttpServletRequest request,HttpServletResponse response) throws Exception {
      //获取请求的页码
      Integer pageNo;
      if (request.getParameter("pageNo")==null){
        pageNo=1;
      }else{
        pageNo=Integer.valueOf(request.getParameter("pageNo"));
      }
      //获取当前访问的用户
      User user = (User) request.getSession().getAttribute(BookStoreConstants.LOGINUSER_SESSIONKEY);
      System.out.println(user.getUserId());
      try{
        //调用业务层的方法执行分页，返回Page对象
        Page<Order> orderList= orderService.getOrderPage(pageNo,user.getUserId());
        //将Page对象存储到请求域中
        request.setAttribute("orderPage",orderList);
        //将PageBean对象序列化为json然后返回给html
        ObjectMapper mapper=new ObjectMapper();
        response.setContentType("application/json;charset=utf-8");
        mapper.writeValue(response.getOutputStream(),orderList);

      }catch (Exception e){
        e.printStackTrace();
        //跳转到统一的异常提示页面
        //往request域对象中存放异常信息
        request.setAttribute("errorMsg",e.getMessage());
        processTemplate("error",request,response);
      }
    }

  //管理订单页面
  public void managerOrderPage(HttpServletRequest request,HttpServletResponse response) throws Exception {
    //获取请求的页码
    Integer pageNo;
    if (request.getParameter("pageNo")==null){
      pageNo=1;
    }else{
      pageNo=Integer.valueOf(request.getParameter("pageNo"));
    }
    try{
      //调用业务层的方法执行分页，返回Page对象
      Page<Order> orderList= orderService.getOrderPageByManager(pageNo);
      //将Page对象存储到请求域中
      request.setAttribute("orderPage",orderList);
      //将PageBean对象序列化为json然后返回给html
      ObjectMapper mapper=new ObjectMapper();
      response.setContentType("application/json;charset=utf-8");
      mapper.writeValue(response.getOutputStream(),orderList);

    }catch (Exception e){
      e.printStackTrace();
      //跳转到统一的异常提示页面
      //往request域对象中存放异常信息
      request.setAttribute("errorMsg",e.getMessage());
      processTemplate("error",request,response);
    }
  }

  //订单详情
  public void showOrderDetails(HttpServletRequest request, HttpServletResponse response) throws IOException {
    //获取订单编号
    Integer orderId=Integer.valueOf(request.getParameter("orderId"));
    Integer orderStatus=Integer.valueOf(request.getParameter("orderStatus"));
    try{
      List<OrderItem> orderItem=orderService.getOrderDetails(orderId);
      Integer totalCount=0;
      Double totalAmount=0.00;
      for (OrderItem item :  orderItem){
        totalCount +=item.getItemCount();
        totalAmount+=item.getItemAmount();
      }
      request.setAttribute("orderItem",orderItem);
      request.setAttribute("totalCount",totalCount);
      request.setAttribute("totalAmount",totalAmount);
      request.setAttribute("orderId",orderId);
      request.setAttribute("orderStatus",orderStatus);
      //跳转到当前页面
      //查询成功，解析Thymeleaf模板
      processTemplate("order/orderDetail", request, response);

    }catch (Exception e){
      e.printStackTrace();
      //跳转到统一的异常提示页面
      //往request域对象中存放异常信息
      request.setAttribute("errorMsg",e.getMessage());
      processTemplate("error",request,response);
    }
  }
  //点击发货/确认收货
  public void send(HttpServletRequest request, HttpServletResponse response) throws IOException {
    //获取订单编号
    Integer orderId=Integer.valueOf(request.getParameter("orderId"));
    Integer orderStatus=Integer.valueOf(request.getParameter("orderStatus"));
    try{
      orderService.send(orderId,orderStatus);
    }catch (Exception e){
      e.printStackTrace();
      //跳转到统一的异常提示页面
      //往request域对象中存放异常信息
      request.setAttribute("errorMsg",e.getMessage());
      processTemplate("error",request,response);
    }
  }
  //退货
  public void orderCancel(HttpServletRequest request, HttpServletResponse response) throws IOException {
    Integer orderId=Integer.valueOf(request.getParameter("orderId"));
    try{
      orderService.orderCancel(orderId);
    }catch (Exception e){
      e.printStackTrace();
      //跳转到统一的异常提示页面
      //往request域对象中存放异常信息
      request.setAttribute("errorMsg",e.getMessage());
      processTemplate("error",request,response);
    }
  }
}
